package com.yunjian.common.redis;

import com.alibaba.fastjson.JSON;
import com.yunjian.common.utils.BeanUtilsExtends;
import org.apache.log4j.Logger;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Redis工具类
 */
@Component
public class RedisUtils {
    private final Logger log = Logger.getLogger(getClass());
    @Resource
    private RedisTemplate redisTemplate;
    @Resource(name="valueOperations")
    private ValueOperations<String, String> valueOperations;
    @Resource(name="hashOperations")
    private HashOperations<String, String, Object> hashOperations;
    @Resource(name="listOperations")
    private ListOperations<String, Object> listOperations;
    @Resource(name="setOperations")
    private SetOperations<String, Object> setOperations;
    @Resource(name="zSetOperations")
    private ZSetOperations<String, Object> zSetOperations;
    // 默认过期时长，单位：秒
    public final static long DEFAULT_EXPIRE = 60 * 60 * 24;
    // 不设置过期时长
    public final static long NOT_EXPIRE = -1;

    public void set(String key, Object value, long expire){
        valueOperations.set(key, toJson(value));
        if(expire != NOT_EXPIRE){
            this.expire(key, expire);
        }
    }

    public void set(String key, Object value){
        set(key, value, NOT_EXPIRE);
    }

    public <T> T get(String key, Class<T> clazz, long expire) {
        String value = valueOperations.get(key);
        if(expire != NOT_EXPIRE){
            this.expire(key, expire);
        }
        return value == null ? null : fromJson(value, clazz);
    }

    public <T> T get(String key, Class<T> clazz) {
        return get(key, clazz, NOT_EXPIRE);
    }

    public String get(String key, long expire) {
        String value = valueOperations.get(key);
        if(expire != NOT_EXPIRE){
            this.expire(key, expire);
        }
        return value;
    }

    public String get(String key) {
        return get(key, NOT_EXPIRE);
    }

    public void expire(String key, long expire){
        redisTemplate.expire(key, expire, TimeUnit.SECONDS);
    }

    public void delete(String key) {
        redisTemplate.delete(key);
    }

    public void setMap(String key, Map<String, String> map, long expire){
        hashOperations.putAll(key, map);
        if(expire != NOT_EXPIRE){
            this.expire(key, expire);
        }
    }

    public void setMap(String key, Map<String, String> map){
        setMap(key, map, NOT_EXPIRE);
    }

    public Map<String, Object> getMap(String key, long expire){
        Map<String, Object> map = hashOperations.entries(key);
        if(expire != NOT_EXPIRE){
            this.expire(key, expire);
        }
        return map;
    }

    public Map<String, Object> getMap(String key){
        return getMap(key, NOT_EXPIRE);
    }

    public void setHash(String key, Object value, long expire){
        Map<String, String> map = BeanUtilsExtends.transBean2MapStr(value);
        setMap(key,map,expire);
    };

    public void setHash(String key, Object value){
        setHash(key,value,NOT_EXPIRE);
    };

    public <T> T getHash(String key, Class<T> clazz, long expire){
        try {
            Map<String, Object> mapObj = this.getMap(key);
            Map<String, String> mapStr = BeanUtilsExtends.transMapObj2MapStr(mapObj);
            T obj = clazz.newInstance();
            if (!CollectionUtils.isEmpty(mapStr)) {
                BeanUtilsExtends.transMapStr2Bean(mapStr, obj);
                if(expire != NOT_EXPIRE) {
                    this.expire(key, expire);
                }
                return obj;
            }
        } catch (Exception e) {
            log.error("获取key" + key);
            log.error("转换字符串为"+clazz+"对象错误", e);
        }
        return null;
    }

    public <T> T getHash(String key, Class<T> clazz){
        return getHash(key,clazz,NOT_EXPIRE);
    }

    /**
     * Object转成JSON数据
     */
    private String toJson(Object object){
        if(object instanceof Integer || object instanceof Long || object instanceof Float ||
                object instanceof Double || object instanceof Boolean || object instanceof String){
            return String.valueOf(object);
        }
        return JSON.toJSONString(object);
    }

    /**
     * JSON数据，转成Object
     */
    private <T> T fromJson(String json, Class<T> clazz){
        return JSON.parseObject(json, clazz);
    }
}
